package com.zhudi.advice;

import com.zhudi.expection.BusinessException;
import com.zhudi.service.UserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import static com.zhudi.contant.UserContant.USER_LOGIN_STATE;
import static com.zhudi.model.enums.ErrorCode.*;

@Component
@Aspect
/**
 * 用于身份检查的切面类
 */
public class PermissionAdvice {

    @Resource
    private UserService userService;


    /**
     * 检查是否登录的切面
     */
    @Before("@annotation(com.zhudi.annotation.UserLoginCheck)")
    public void UserLoginCheck(JoinPoint joinPoint){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        if (servletRequestAttributes==null){
            throw new BusinessException(NOT_LOGIN);
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Object loginUser = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (loginUser==null){
            throw new BusinessException(NOT_LOGIN);
        }

    }


}
